package com.hgk.wanwan.main.fragment.persentfragment.alarmclock;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.hgk.common.common.ui.activity.BallTitleAcitivty;
import com.hgk.common.common.ui.photoview.GestureDetector;
import com.hgk.common.common.ui.photoview.OnGestureListener;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;

import width.hgk.wanwan.R;

public class AlarmActivity extends BallTitleAcitivty implements View.OnTouchListener {

    private TextView tvAdd;// 添加
    private Toast toastStart;
    private Date currentTime;
    private Date beginTime = null;
    private ListView mlistview;
    private SimpleAdapter mlistItemAdapter;
    private ArrayList<HashMap<String, Object>> mlistItem = null;
    private DatabaseHelper dbHelper;
    int index = 0;// 长按删除指定数据的索引
    static int Alarming_index = 0;// 闹铃响时所对应的数据库_id
    private GestureDetector mGestureDetector; // 手势切换查看历史

    /** Called when the activity is first created. */
    @Override
    public void onResume() {
        super.onResume();
//        setContentView(R.layout.main);
        System.out.println("mainActivyt-->resume");
        tvAdd = (TextView) findViewById(R.id.add);
        toastStart = new Toast(this);
        tvAdd.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent = new Intent(mContext, EditTimeActivity.class);
                intent.putExtra("click_key", "click_add");
                startActivity(intent);
            }
        });
        // 手势的使用
        mGestureDetector = new GestureDetector() {
            @Override
            public boolean onTouchEvent(MotionEvent ev) {
                return false;
            }

            @Override
            public boolean isScaling() {
                return false;
            }

            @Override
            public boolean isDragging() {
                return false;
            }

            @Override
            public void setOnGestureListener(OnGestureListener listener) {

            }
        };
        // 两个控件同时加上手势监听
        LinearLayout mlayout = (LinearLayout) findViewById(R.id.mainlayout);
        mlayout.setOnTouchListener(this);
        mlayout.setLongClickable(true);

        mlistview = (ListView) findViewById(R.id.mlistview);
        mlistview.setOnTouchListener(this);
        mlistview.setLongClickable(true);
        mlistItem = new ArrayList<HashMap<String, Object>>();

        dbHelper = new DatabaseHelper(AlarmActivity.this, "ideal.sql");

        SQLiteDatabase db = dbHelper.getReadableDatabase();

        // 以下是把所有的表都存进来，然后_id按顺序排列，方便读取数据
        Cursor cursor = db.query("user", null, null, null, null, null, null);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm");
        if (cursor.moveToLast()) {

            currentTime = new Date();
            try {
                beginTime = sdf.parse(cursor.getString(cursor
                        .getColumnIndex("mtime")));
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // 默认为毫秒，除以1000是为了转换成秒
            long interval_last = (beginTime.getTime() - currentTime.getTime()) / 1000;// 秒
            long dayTemp_last = interval_last / (24 * 3600);// 天
            long hourTemp_last = interval_last % (24 * 3600) / 3600;// 小时
            long minuteTemp_last = interval_last % 3600 / 60;// 分钟
            HashMap<String, Object> map_last = new HashMap<String, Object>();
            map_last.put("mtext",
                    cursor.getString(cursor.getColumnIndex("mtext")));
            map_last.put("mtime", dayTemp_last + " 天 " + hourTemp_last + " 时 "
                    + (minuteTemp_last + 1)+" 分");
            mlistItem.add(map_last);
            while (cursor.moveToPrevious()) {
                String mtext = cursor.getString(cursor.getColumnIndex("mtext"));
                String mtime = cursor.getString(cursor.getColumnIndex("mtime"));

                currentTime = new Date();
                try {
                    beginTime = sdf.parse(mtime);
                } catch (ParseException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                // 默认为毫秒，除以1000是为了转换成秒
                long interval = (beginTime.getTime() - currentTime.getTime()) / 1000;// 秒
                long dayTemp = interval / (24 * 3600);// 天
                long hourTemp = interval % (24 * 3600) / 3600;// 小时
                long minuteTemp = interval % 3600 / 60;// 分钟
                HashMap<String, Object> map = new HashMap<String, Object>();
                map.put("mtext", mtext);
                map.put("mtime", dayTemp + " 天 " + hourTemp + " 时 "
                        + (minuteTemp + 1)+" 分");
                mlistItem.add(map);
            }
        }

        mlistItemAdapter = new SimpleAdapter(
                getApplicationContext(),
                mlistItem,// 数据源
                R.layout.listviewitem, new String[] { "mtext", "mtime" },
                new int[] { R.id.ItemText, R.id.ItemTime });

        mlistview.setAdapter(mlistItemAdapter);
        db.close();
        // 每秒进行刷新一次
        new TimeThread().start();
        // 点击
        mlistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String text = mlistItem.get(position).get("mtext").toString();
                String time = mlistItem.get(position).get("mtime").toString();
                Intent intent = new Intent(AlarmActivity.this, EditTimeActivity.class);
                intent.putExtra("click_key", "click_edit");
                intent.putExtra("text", text);
                intent.putExtra("time", time);
                startActivity(intent);
            }
        });
        // 添加长按点击,得到点中的index，即参数arg2
        mlistview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                index = position;
                return false;
            }
        });
        // 长按之后跳出可选的Menu框
        mlistview.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                menu.setHeaderTitle("选择操作");
                menu.add(0, 0, 0, "删除");
                menu.add(0, 1, 1, "取消");
            }
        });
    }

    // 长按菜单响应函数
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:// 删除指定记录
                String deleteText = mlistItem.get(index).get("mtext").toString();
                String deleteTime = mlistItem.get(index).get("mtime").toString();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm");
                SQLiteDatabase db = dbHelper.getReadableDatabase();
                // 以下是把所有的表都存进来，然后_id按顺序排列，方便读取数据
                Cursor cursor = db
                        .query("user", null, null, null, null, null, null);
                while (cursor.moveToNext()) {
                    String mtext = cursor.getString(cursor.getColumnIndex("mtext"));// 得到数据库中的数据
                    String mtime = cursor.getString(cursor.getColumnIndex("mtime"));
                    currentTime = new Date();
                    try {
                        beginTime = sdf.parse(mtime);
                    } catch (ParseException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    // 默认为毫秒，除以1000是为了转换成秒
                    long interval = (beginTime.getTime() - currentTime.getTime()) / 1000;// 秒
                    long dayTemp = interval / (24 * 3600);// 天
                    long hourTemp = interval % (24 * 3600) / 3600;// 小时
                    long minuteTemp = interval % 3600 / 60;// 分钟
                    String Cursortime = dayTemp + " 天 " + hourTemp + " 时 "
                            + (minuteTemp + 1)+" 分";
                    // 通过主键值来判断点中的listview中的Item所对应的数据库表中的_id,同时删除其闹铃

                    // 闹铃删除
                    AlarmManager mAlarm;
                    mAlarm = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
                    Intent intent = new Intent(AlarmActivity.this,
                            AlarmReceiver.class);
                    if (deleteText.equals(mtext) && deleteTime.equals(Cursortime)) {

                        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                                AlarmActivity.this, cursor.getInt(0), intent, 0);// 第二个参数为区别不同闹铃的唯一标识
                        mAlarm.cancel(pendingIntent);
                        // 添加进历史
                        addData(mtime, mtext);
                        // 数据库删除
                        deleteData(cursor.getInt(0));// 删除匹配的数据库里记录，cursor.getInt(0)为得到该cursor对用的第一例，及_id
                        break;
                    }
                    db.close();
                }
                Intent mWidgetIntent = new Intent();
                mWidgetIntent.setAction("com.ideal.note.widget");
                AlarmActivity.this.sendBroadcast(mWidgetIntent);

                break;
            default:
                break;
        }
        return super.onContextItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        menu.add(0, 2, 2, "查看历史").setIcon(
                android.R.drawable.ic_menu_recent_history);
        menu.add(0, 3, 3, "删除所有").setIcon(android.R.drawable.ic_menu_delete);
        menu.add(0, 4, 4, "关于我们").setIcon(android.R.drawable.ic_menu_help);
        menu.add(0, 5, 5, "退出").setIcon(
                android.R.drawable.ic_menu_close_clear_cancel);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
            case 2:// 查看历史
                Intent i = new Intent(AlarmActivity.this, HaveDone.class);
                startActivity(i);
                break;
            case 3:// 删除所有
                // 所有闹铃删除
                new AlertDialog.Builder(AlarmActivity.this)
                        .setTitle("确定删除所有？")
                        .setPositiveButton("删除",
                                new DialogInterface.OnClickListener() {

                                    @Override
                                    public void onClick(DialogInterface dialog,
                                                        int which) {
                                        // TODO Auto-generated method stub
                                        AlarmManager mAlarm;
                                        PendingIntent pendingIntent;
                                        mAlarm = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
                                        Intent intent_del = new Intent(
                                                AlarmActivity.this,
                                                AlarmReceiver.class);
                                        SQLiteDatabase db = dbHelper
                                                .getReadableDatabase();
                                        // 以下是把所有的表都存进来，然后_id按顺序排列，方便读取数据
                                        Cursor cursor = db.query("user", null,
                                                null, null, null, null, null);
                                        while (cursor.moveToNext()) {
                                            pendingIntent = PendingIntent
                                                    .getBroadcast(
                                                            AlarmActivity.this,
                                                            cursor.getInt(0),
                                                            intent_del, 0);// 第二个参数为区别不同闹铃的唯一标识
                                            mAlarm.cancel(pendingIntent);
                                        }
                                        deleteTable();
                                        setContentView(R.layout.main);
                                        Intent mWidgetIntent = new Intent();
                                        mWidgetIntent.setAction("com.ideal.note.widget");
                                        AlarmActivity.this.sendBroadcast(mWidgetIntent);
                                    }
                                }).setNegativeButton("取消", null).show();

                break;
            case 4: // 关于我们
                View view = getLayoutInflater().inflate(R.layout.toast, null);
                toastStart.setGravity(Gravity.BOTTOM, 0, 10);
                toastStart.setDuration(Toast.LENGTH_LONG);
                toastStart.setView(view);
                toastStart.show();
                break;
            case 5:// 退出
                finish();
                break;
            default:
                break;
        }
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public void setLeftButton(RelativeLayout relativeLayout, Button button) {

    }

    @Override
    public void setRightButton(RelativeLayout relativeLayout, Button button) {

    }

    @Override
    public Object getTitleString() {
        return "我的闹钟";
    }

    @Override
    public int getBodyView() {
        return R.layout.main;
    }


    // 开启一个线程，以便每秒更新数据一次
    public class TimeThread extends Thread {
        @Override
        public void run() {
            do {
                try {
                    Thread.sleep(1000);
                    Message msg = new Message();
                    msg.what = 1;
                    mHandler.sendMessage(msg);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            } while (true);
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    // 清除原来的数据并更新mlistItemAdapter
                    mlistItem.clear();
                    mlistItemAdapter.notifyDataSetChanged();
                    // 获取最新时间
                    currentTime = new Date();
                    SQLiteDatabase db = dbHelper.getReadableDatabase();
                    Cursor cursor = db.query("user", null, null, null, null, null,
                            null);
                    // 时间格式转化
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm");
                    if (cursor.moveToLast()) {
                        currentTime = new Date();
                        try {
                            beginTime = sdf.parse(cursor.getString(cursor
                                    .getColumnIndex("mtime")));
                        } catch (ParseException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        // 默认为毫秒，除以1000是为了转换成秒
                        long interval_last = (beginTime.getTime() - currentTime
                                .getTime()) / 1000;// 秒
                        if (((Math.abs(beginTime.getTime() - currentTime.getTime())) < 10000)
                                && cursor.getLong(cursor.getColumnIndex("isalarm")) == 1) {// 这句非常重要
                            System.out.println("alarming_index-->"+Alarming_index);
                            Alarming_index = cursor.getInt(0);
                        }

                        long dayTemp_last = interval_last / (24 * 3600);// 天
                        long hourTemp_last = interval_last % (24 * 3600) / 3600;// 小时
                        long minuteTemp_last = interval_last % 3600 / 60;// 分钟
                        long secondTemp_last = interval_last % 60;
                        HashMap<String, Object> map_last = new HashMap<String, Object>();
                        map_last.put("mtext",
                                cursor.getString(cursor.getColumnIndex("mtext")));
                        map_last.put("mtime", dayTemp_last + " 天 " + hourTemp_last
                                + " 时 " + (minuteTemp_last + 1)+" 分");
                        mlistItem.add(map_last);

                        while (cursor.moveToPrevious()) {
                            String mtext = cursor.getString(cursor
                                    .getColumnIndex("mtext"));
                            String mtime = cursor.getString(cursor
                                    .getColumnIndex("mtime"));
                            currentTime = new Date();
                            try {
                                beginTime = sdf.parse(mtime);
                            } catch (ParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                            // 默认为毫秒，除以1000是为了转换成秒
                            long interval = (beginTime.getTime() - currentTime
                                    .getTime()) / 1000;// 秒
                            // 达到后删除条记录
                            if (((Math.abs(beginTime.getTime() - currentTime.getTime())) < 10000)
                                    && cursor.getLong(cursor
                                    .getColumnIndex("isalarm")) == 1) {// 这句非常重要
                                System.out.println("alarming_index-->"+Alarming_index);
                                Alarming_index = cursor.getInt(0);
                            }

                            long dayTemp = interval / (24 * 3600);// 天
                            long hourTemp = interval % (24 * 3600) / 3600;// 小时
                            long minuteTemp = interval % 3600 / 60;// 分钟
                            long secondTemp = interval % 60;

                            HashMap<String, Object> map = new HashMap<String, Object>();
                            map.put("mtext", mtext);
                            map.put("mtime", dayTemp + " 天 " + hourTemp + " 时 "
                                    + (minuteTemp + 1)+" 分");
                            mlistItem.add(map);
                        }
                    }

                    mlistItemAdapter = new SimpleAdapter(
                            getApplicationContext(),
                            mlistItem,// 数据源
                            R.layout.listviewitem,
                            new String[] { "mtext", "mtime" }, new int[] {
                            R.id.ItemText, R.id.ItemTime });

                    mlistview.setAdapter(mlistItemAdapter);
                    db.close();
                    break;

                default:
                    break;
            }
        }
    };

    public void addData(String mtime, String mtext) {
        ContentValues values = new ContentValues();
        values.put("mtime", mtime);
        values.put("mtext", mtext);
        SQLiteDatabase db_w = dbHelper.getWritableDatabase();
        db_w.insert("user_done", null, values);
        db_w.close();
        // toast记录有多少条
        SQLiteDatabase db_r = dbHelper.getReadableDatabase();
        Cursor cursor = db_r.query("user_done", null, null, null, null, null,
                null);
        Toast.makeText(AlarmActivity.this, cursor.getCount() + "",
                Toast.LENGTH_SHORT).show();
        db_r.close();
    }

    public void deleteData(int index) {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        // 删除表的所有数据
        // db.delete("users",null,null);
        // 从表中删除指定的一条数据
        db.execSQL("DELETE FROM " + "user" + " WHERE _id="
                + Integer.toString(index));
        db.close();
    }

    public void deleteTable() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        try {
            // 执行SQL语句
            db.execSQL("drop table user"); // 删除表
        } catch (SQLException e) {
        }
        this.deleteDatabase("ideal.sql");// 删除一个数据库，只要有这个数据库，填入数据库名即可删除
        db.close();
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        return mGestureDetector.onTouchEvent(event);
    }
    public static void launch(Context context){
        context.startActivity(new Intent(context,AlarmActivity.class));
    }
}
